<template>
  <div class="center">
    <n-card :bordered="false">
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        :submitButtonText="'查询'"
        :resetButtonText="'重置'"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
      >
        <template #tableTitle>
          <n-space>
            <n-button size="small" @click="addTable"> 新增 </n-button>
            <n-button size="small"> 批量导入 </n-button>
          </n-space>
        </template>
      </BasicTable>
    </n-card>
    <Model
      :showModal="showModal"
      :FormData="FormData"
      :formValue="formValue"
      :title="title"
      @ModelClick="onAdd"
      @close="close"
    />
    <!--    <ModelBox-->
    <!--      :ModelBox="ModelBox"-->
    <!--      :center="center"-->
    <!--      :title="title"-->
    <!--      @ModelClick="ModelClick"-->
    <!--      @close="close"-->
    <!--    />-->
  </div>
</template>

<script lang="ts">
  import { h, defineComponent, reactive, ref, toRaw } from 'vue';
  import { NPopconfirm, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { PlusOutlined } from '@vicons/antd';
  import { useRouter } from 'vue-router';
  import { Model } from '@/components/Model';
  import { ModelBox } from '@/components/ModelBox';
  import {
    addDriver,
    addEnterprise,
    deleteDriver,
    deleteEnterprise,
    getDriverList,
    saveDriver,
    saveEnterprise,
  } from '@/api/BaseInfo';
  export default defineComponent({
    components: {
      BasicTable,
      BasicForm,
      PlusOutlined,
      Model,
      ModelBox,
    },
    setup() {
      const rules = {
        name: { required: true, trigger: ['blur', 'input'], message: '请输入名称' },
        address: { required: true, trigger: ['blur', 'input'], message: '请输入地址' },
        date: {
          type: 'number',
          required: true,
          trigger: ['blur', 'change'],
          message: '请选择日期',
        },
      };

      const columns = [
        {
          title: '序号',
          key: '',
          width: 100,
          render(row, index) {
            return index + 1;
          },
        },
        {
          title: '驾驶人',
          key: 'name',
          width: 100,
        },
        {
          title: '性别',
          key: 'sex',
          width: 100,
          render(row) {
            return row.sex === 1 ? '男' : '女';
          },
        },
        {
          title: '联系方式',
          key: 'address',
          width: 150,
        },
        {
          title: '所属企业',
          key: 'enterpriseName',
          width: 100,
        },
        {
          title: '状态',
          key: 'status',
          width: 100,
          render(row) {
            return row.status === 1 ? '启用' : '停用';
          },
        },
        {
          title: '行驶证',
          key: '',
          width: 100,
        },
        {
          title: '从业证',
          key: '',
          width: 100,
        },
      ];
      const router = useRouter();
      const formRef: any = ref(null);
      const center = ref(null);
      const message = useMessage();
      const actionRef = ref();
      const title = ref(null);
      const showModal = ref(false);
      const ModelBox = ref(false);
      const formBtnLoading = ref(false);
      const formValue = ref({});
      const FormData = ref([
        {
          label: '姓名',
          type: 'n-input',
          enName: 'name',
          clearable: true,
          show: true,
          show: true,
          size: 'small',
          placeholder: '请输入姓名',
          span: 12,
        },
        {
          label: '联系电话',
          type: 'n-input',
          enName: 'mobile',
          clearable: true,
          show: true,
          size: 'small',
          placeholder: '请输入联系电话',
          span: 12,
        },
        {
          label: '性别',
          type: 'n-select',
          enName: 'sex',
          clearable: true,
          show: true,
          size: 'small',
          placeholder: '请选择性别',
          span: 12,
          options: [
            { label: '男', value: '1' },
            { label: '女', value: '2' },
          ],
        },
        {
          label: '身份证号',
          type: 'n-input',
          enName: 'idCard',
          clearable: true,
          show: true,
          size: 'small',
          placeholder: '请输入身份证号码',
          span: 12,
        },
        {
          label: '身份证有效期',
          type: 'n-input',
          enName: 'youxiaoqi',
          clearable: true,
          show: true,
          size: 'small',
          placeholder: '请输入有效期',
          span: 12,
        },
        {
          label: '户籍所在地',
          type: 'n-input',
          // type: 'n-select',
          enName: 'address',
          clearable: true,
          show: true,
          size: 'small',
          placeholder: '请选择',
          // options: [
          //   { label: '浙江省', value: 1 },
          //   { label: '安徽省', value: 2 },
          // ],
          span: 12,
        },
        {
          label: '所属企业',
          type: 'n-select',
          enName: 'enterpriseId',
          clearable: true,
          show: true,
          size: 'small',
          placeholder: '请选择',
          options: [
            { label: '企业1', value: '1' },
            { label: '企业2', value: '2' },
          ],
          span: 12,
        },
        {
          label: '所属部门',
          type: 'n-select',
          enName: 'departmentId',
          clearable: true,
          show: true,
          size: 'small',
          placeholder: '请选择',
          options: [
            { label: '部门1', value: '1' },
            { label: '部门2', value: '2' },
          ],
          span: 12,
        },
        {
          type: 'n-collapse',
          show: true,
          options: [
            {
              title: '驾驶证信息',
              name: '1',
              chidlren: [
                {
                  label: '准驾车型',
                  type: 'n-input',
                  enName: 'code',
                  clearable: true,
                  show: true,
                  size: 'small',
                  placeholder: '请输入准驾车型',
                  span: 12,
                },
                {
                  label: '驾驶证号',
                  type: 'n-input',
                  enName: 'jigou',
                  clearable: true,
                  show: true,
                  size: 'small',
                  placeholder: '请输入驾驶证号',
                  span: 12,
                },
                {
                  label: '驾驶证档案编号',
                  type: 'n-input',
                  enName: 'youxiaoqi',
                  clearable: true,
                  show: true,
                  size: 'small',
                  placeholder: '请输入驾驶证档案编号',
                  span: 12,
                },
                {
                  label: '驾驶证有效期',
                  type: 'n-input',
                  enName: 'youxiaoqi',
                  clearable: true,
                  show: true,
                  size: 'small',
                  placeholder: '请输入驾驶证有效期',
                  span: 12,
                },
                {
                  label: '驾驶证照片',
                  type: 'n-upload',
                  enName: 'code',
                  clearable: true,
                  show: true,
                  size: 'small',
                  span: 12,
                  name: '点击上传',
                },
              ],
            },
            {
              title: '从业证信息',
              name: '1',
              chidlren: [
                {
                  label: '从业证号',
                  type: 'n-input',
                  enName: 'zhenghao',
                  clearable: true,
                  show: true,
                  size: 'small',
                  placeholder: '请输入从业证号',
                  span: 12,
                },
                {
                  label: '从业证核发地',
                  type: 'n-input',
                  enName: 'hefadi',
                  clearable: true,
                  show: true,
                  size: 'small',
                  placeholder: '请输入从业证核发地',
                  span: 12,
                },
                {
                  label: '从业证有效期',
                  type: 'n-input',
                  enName: 'youxiaoqi',
                  clearable: true,
                  show: true,
                  size: 'small',
                  placeholder: '请输入从业证有效期',
                  span: 12,
                },
                {
                  label: '从业证照片',
                  type: 'n-upload',
                  enName: 'code',
                  clearable: true,
                  show: true,
                  size: 'small',
                  span: 12,
                  name: '点击上传',
                },
              ],
            },
          ],
          span: 24,
        },
      ]);
      const formParams = ref({
        name: '',
        address: '',
        date: null,
      });

      const params = ref({
        pageSize: 10,
        name: 'xiaoMa',
      });

      const setSRecordStatus = async (record, isEnable) => {
        await saveDriver({ ...record, isEnable: isEnable });
        reloadTable();
      };

      const deleteRecord = async (id) => {
        try {
          await deleteDriver(id);
          message.success('删除成功！');
          reloadTable();
        } catch (e) {
          message.error('删除失败');
        }
      };
      const onAdd = function (e) {
        showModal.value = e;
        ModelBox.value = e;
        message.success('添加');
        const keyDicts = Object.values(FormData.value);
        const dataDict = {};
        for (let i = 0; i < keyDicts.length; i++) {
          const keyItem = keyDicts[i];
          const key = keyItem['enName'];
          dataDict[key] = formValue.value[key];
        }
        addDriver(JSON.parse(JSON.stringify(formValue.value)))
          .then((res) => {
            message.success('添加成功！');
            reloadTable();
          })
          .catch((e) => {
            message.error('添加失败！');
          });
      };
      const actionColumn = reactive({
        width: 220,
        title: '操作',
        key: 'action',
        fixed: 'right',
        render(record) {
          const isEnableStr = record.isEnable === 1 ? '停用' : '启用';
          return h(
            'div',
            {
              style: 'display: flex; align-items: center;',
            },
            [
              h(TableAction as any, {
                text: true,
                actions: [
                  {
                    label: '查看',
                    type: 'primary',
                    text: true,
                    onClick: see.bind(null, record),
                  },
                  {
                    label: '编辑',
                    type: 'primary',
                    text: true,
                    onClick: handleEdit.bind(null, record),
                  },
                  // {
                  //   label: '删除',
                  //   type: 'primary',
                  //   text: true,
                  //   onClick: handleDelete.bind(null, record),
                  // },
                ],
                select: (key) => {
                  message.info(`您点击了，${key} 按钮`);
                },
              }),
              h(
                NPopconfirm,
                {
                  onPositiveClick: () => {
                    const isEnable = record.isEnable === 1 ? 0 : 1;
                    setSRecordStatus(record, isEnable);
                  },
                },
                {
                  trigger: h(
                    'div',
                    {
                      style: 'color: var(--th-icon-color-active);cursor: pointer;margin: 0 8px;',
                    },
                    isEnableStr
                  ),
                  default: [h('div', `是否确定要${isEnableStr}“${record.name}”`)],
                }
              ),
              h(
                NPopconfirm,
                {
                  onPositiveClick: () => {
                    console.log(record);
                    deleteRecord(record.id);
                  },
                },
                {
                  trigger: h(
                    'div',
                    {
                      style: 'color: var(--th-icon-color-active);cursor: pointer;margin: 0 8px;',
                    },
                    '删除'
                  ),
                  default: [h('div', `是否确定要删除“${record.name}”`)],
                }
              ),
            ]
          );
        },
      });
      const schemas = [
        {
          field: 'name',
          component: 'NSelect',
          label: '行业领域',
          size: 'small',
          componentProps: {
            placeholder: '请选择行业领域',
            options: [
              {
                label: '行业领域1',
                value: 1,
              },
              {
                label: '行业领域2',
                value: 2,
              },
            ],
            onInput: (e: any) => {
              console.log(e);
            },
          },
        },
        {
          field: 'name',
          component: 'NSelect',
          label: '企业',
          size: 'small',
          componentProps: {
            placeholder: '请选择企业',
            options: [
              {
                label: '企业1',
                value: 1,
              },
              {
                label: '企业2',
                value: 2,
              },
            ],
            onInput: (e: any) => {
              console.log(e);
            },
          },
        },
      ];
      const [register, {}] = useForm({
        gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
        labelWidth: 80,
        schemas,
      });
      const loadDataTable = async (res) => {
        console.log(res);
        return await getDriverList({ ...res, ...formParams, ...params.value });
      };

      const onCheckedRow = (rowKeys) => {
        console.log(rowKeys);
      };

      const reloadTable = () => {
        actionRef.value.reload();
      };
      const Deactivate = (record: Recordable) => {
        ModelBox.value = true;
        title.value = '停用&启用';
        center.value = '是否确定要停用&启用';
      };

      const handleEdit = (record: Recordable) => {
        router.push({ name: 'driverDetails', params: { id: record.id } });
      };

      const handleDelete = (record: Recordable) => {
        ModelBox.value = true;
        title.value = '删除';
        center.value = '是否确定要删除?';
      };
      const see = (record: Recordable) => {
        router.push({ name: 'driverDetails', params: { id: record.id } });
      };

      //查询
      const handleSubmit = (row) => {};

      //新增
      const addTable = () => {
        title.value = '新增驾驶人';
        showModal.value = true;
      };

      //模态框确定按钮
      const ModelClick = (e) => {
        showModal.value = e;
        ModelBox.value = e;
      };
      //模态框关闭
      const close = (e) => {
        showModal.value = e;
        ModelBox.value = e;
      };
      return {
        addTable,
        rules,
        schemas,
        router,
        formRef,
        message,
        actionRef,
        showModal,
        ModelBox,
        formBtnLoading,
        formParams,
        params,
        actionColumn,
        register,
        loadDataTable,
        onCheckedRow,
        reloadTable,
        Deactivate,
        handleEdit,
        handleDelete,
        see,
        columns,
        handleSubmit,
        onAdd,
        close,
        title,
        FormData,
        formValue,
        center,
      };
    },
  });
</script>

<style lang="less" scoped>
  .center :deep .n-card {
    margin: 0 0 20px 0;
  }
</style>
